import openai
import json


class GPTBasedAgent(IntelligentAgent):
    def __init__(self, name, api_key, model="gpt-3.5-turbo"):
        super().__init__(name)
        self.model = model
        openai.api_key = api_key
        self.conversation_history = []

    def think(self, perception):
        """使用 GPT 进行思考决策"""
        prompt = f"""
        你是一个智能体，当前感知到: {perception}
        请分析情况并做出最佳决策。
        可选动作: [探索, 攻击, 防御, 收集, 休息, 逃跑]
        请以JSON格式回复: {{"action": "选择的动作", "reason": "理由"}}
        """

        try:
            response = openai.ChatCompletion.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": "你是一个智能决策助手"},
                    {"role": "user", "content": prompt}
                ]
            )

            decision_text = response.choices[0].message.content
            decision = json.loads(decision_text)
            return decision

        except Exception as e:
            return {"action": "探索", "reason": f"API调用失败: {str(e)}"}

# 使用示例（需要 OpenAI API key）
# gpt_agent = GPTBasedAgent("GPT智能体", "your-api-key")
# decision = gpt_agent.think("发现前方有敌人和资源")
# print(decision)